﻿using Rbac.Contracts.DTO.InPut;
using Rbac.Contracts.DTO.OutPut;
using Rbac.Contracts.Interface;
using Rbac.Domain.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rbac.Server
{
	public class RolePermissionServer:ServerBase,IRolePermissionServer
	{
		private readonly IRolePermissionRepository _rolePermissionRepository;
		public RolePermissionServer(IRolePermissionRepository rolePermissionRepository)
		{
			_rolePermissionRepository = rolePermissionRepository;
		}
		/// <summary>
		/// 为角色分配权限
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public int DistributeRolePermissions(DistributeRolePermissionsInput input)
		{
			return _rolePermissionRepository.DistributeRolePermissions(input.RodeId, input.PermissionList);
		}
		/// <summary>
		/// 权限角色获取权限列表
		/// </summary>
		/// <param name="roleId"></param>
		/// <returns></returns>
		public List<PermissionDTO> GetPermissionsByRoleId(int roleId)
		{
			//获取权限列表
			var permissions=
				_rolePermissionRepository.GetPermissionsByRoleId(roleId);
			List < PermissionDTO > result= new();
			foreach(var permission in permissions.Where(c=>c.ParentId==0))
			{
				var dto = _mapper.Map<PermissionDTO>(permission);
				//获取权限子菜单
				var child = permissions.Where(c => c.ParentId == permission.PermissionId);
				if(child.Any())
				{
					dto.Child = _mapper.Map<List<PermissionDTO>>(child);
				}
				result.Add(dto);
			}
			return result;
		}
		/// <summary>
		/// 获取左边菜单栏
		/// </summary>
		/// <param name="roleId"></param>
		/// <returns></returns>
		public List<PermissionDTO> GetMentu(int roleId)
		{
			List<PermissionDTO> result = new();
			//获取角色所有的权限
			var permissions = this.GetPermissionsByRoleId(roleId);
			foreach(var permissionsDto in permissions)
			{
				var child = permissionsDto.Child?.Where(c => c.IsMenu).ToList();
				var dto = new PermissionDTO()
				{
					PermissionId = permissionsDto.PermissionId,
					PermissionName = permissionsDto.PermissionName,
					PermissionUrl = permissionsDto.PermissionUrl,
					Child = child
				};
				result.Add(dto);
			}

			return result;
		}
	}
}
